package dao

import (
	"zy16/inits"
	"zy16/model"
)

func Login(tel string, password string) (result *model.User) {
	err := inits.DB.Where("tel=?", tel).Where("password=?", password).Find(&result).Error
	if err != nil {
		return nil
	}
	return result
}

func Register(tel string, password string) (result *model.User) {
	result = &model.User{
		Tel:      tel,
		Password: password,
	}
	err := inits.DB.Create(&result).Error
	if err != nil {
		return nil
	}
	return result
}

func AddArticles(title string, context string, userId int, num int, articleType int) (result *model.Article) {
	result = &model.Article{
		Title:       title,
		UserId:      userId,
		Context:     context,
		ArticleType: articleType,
		LikeNum:     num,
	}
	err := inits.DB.Create(&result).Error
	if err != nil {
		return nil
	}
	return result
}

func AddFocu(userId int, focuId int) (result *model.Focu) {
	result = &model.Focu{
		UserId: userId,
		FocuId: focuId,
	}
	err := inits.DB.Create(&result).Error
	if err != nil {
		return nil
	}
	return result
}

func List(userId int) []model.Article {
	var result []model.Article
	err := inits.DB.Raw("SELECT e.* FROM article e LEFT JOIN (SELECT focu_id FROM focu WHERE user_id=?) a ON e.user_id=a.focu_id ORDER BY focu_id DESC,like_num DESC", userId).Scan(&result).Error
	if err != nil {
		return []model.Article{}
	}
	return result
}
